package RPC;

import com.rabbitmq.client.*;
import constant.Constant;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RpcServer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 先接收请求再发送响应
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constant.Host);
        connectionFactory.setPort(Constant.Port);
        connectionFactory.setUsername(Constant.userName);
        connectionFactory.setPassword(Constant.userName);
        connectionFactory.setVirtualHost(Constant.VirtualHost);
        Connection connection = connectionFactory.newConnection();

        Channel channel = connection.createChannel();
        // 接受请求
        channel.basicQos(1); // 一次只会接受一条信息
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String request = new String(body,"UTF-8");
                System.out.println("接收到请求: "+request);
                String response = "请求已收到,响应成功!";
                AMQP.BasicProperties basicProperties = new AMQP.BasicProperties()
                        .builder()
                        .correlationId(properties.getCorrelationId())
                        .build();
                channel.basicPublish("",Constant.RPC_RESPONSE_QUEUE,basicProperties,response.getBytes());
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        channel.basicConsume(Constant.RPC_REQUEST_QUEUE,false,consumer);

        channel.close();
        connection.close();
    }
}
